<?php
class svc_mainpage{
	private $args;
	function __construct($arg){
		$this->args = $arg;
	}
	function getPublish(){
		$rs = new Result();
		$lang = $this->args["lang"];
		if($lang == 'bin'){
			$rcode = $this->args['rcode'];
			if($rcode == null || $rcode == '')$rcode = 0;
			$rs->addData("rcode",0 + $rcode);
		}
		$method = $this->args["request"];
		$rs->addData("request",$method);
		if($method == "getSession"){
			$rs->return = true;
			$size = 1 ;
			$buf = ByteBuffer::allocate( $size ) ;
			DataUtil::writeInt8( $buf , 1  ) ;
			$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
		}else if($method == "getTime"){
			$rs->return = true;
			$size = 4 ;
			$buf = ByteBuffer::allocate( $size ) ;
			$time = time() ;
			DataUtil::writeInt32( $buf ,  $time ) ;
			$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
		}else if($method == "getTabs"){
			$rs->addData("0","Main Page");
			$appmng = FunctionData::readAppManager();
			$apps_id = $appmng->getAppsID();
			if(is_array($apps_id)){
				foreach($apps_id as $appid){
					$rs->addData($appid,$appmng->getAppName($appid));
				}
			}
		}else if($method == "debug"){
			$debugid = $this->args["d"];
			if($debugid == "userinfo"){
				$uname = $this->args["uname"];
				$result = "";
				$registed = FunctionData::checkEmailRegisted($uname);
				$id = FunctionData::readAccountId($uname);
				if($id > -1){
					$result .= "this account had been registed with id = ".$id;
				}else{
					if($registed){
						$result .= "This email address had been registed but not confirm <br/>";
						{if(!isset( FunctionData::$static  ) ||  FunctionData::$static  ==null){ FunctionData::$static   = new Memcache; FunctionData::$static  ->connect("127.0.0.1" , 11215 ) or die ("Could not connect");};} ;
						$confirm =  FunctionData::$static  ->get( "mail_confirm_" .$mailaddress ) ;
						if($confirm != null){
							$confirmobj = DataWaitingConfirm::swap(ByteBuffer::wrap( $confirm ) );
							$result .= "confirm code:". $confirmobj->getCode();	
						}else{
							$result .=  "Confirm error, please contact to Administrator";
						}
					}else{
						$result .= "we don't found any infomation about this persion.";
					}
				}
				$rs->return = true;
				$rs->addData("content","Info for ".$uname . "<br/>" . $result);
			}else if($debugid == "leanfbofuser"){
				$uname = $this->args["uname"];
			}
		}else if($method == "getPage"){
			$tools = array(
				array('license_area'=> "AreaRoot"  ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"addgroup");' ,'title'=> "Add Group" ,'icon'=> 'images/' ."add_group.png" ) ,
				array('license_area'=> "AreaRoot"  ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"addarea");' ,'title'=> "Add Area" ,'icon'=> 'images/' ."add_area.png" ) ,
				array('license_area'=> "AccountManagement"  ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"addlicense");' ,'title'=> "Add License" ,'icon'=> 'images/' ."add_license.png" ) ,
				array('license_area'=> "AccountManagement"  ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"usertogroup");' ,'title'=> "U to group" ,'icon'=> 'images/' ."user_mng.png" ) ,
				array('license_area'=> "ApplicationManagement"  ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"createapp");' ,'title'=> "Create App" ,'icon'=> 'images/' ."create_app.png" ) ,
				array('license_area'=> null ,'license_role'=> null ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"changepassword");' ,'title'=> "Change Password" ,'icon'=> 'images/' ."change_password.png" ) ,
				array('license_area'=> null ,'license_role'=> null ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"mngcertificates",document.getElementById("working_panel"));' ,'title'=> "Certificates" ,'icon'=> 'images/' ."certificate_mng.png" ) ,	
				array('license_area'=> null ,'license_role'=> null ,'type'=> 'button' ,'action'=> 'Context.dialog.request(0,"statistic",document.getElementById("working_panel"));' ,'title'=> "Statistic" ,'icon'=> 'images/' ."statistic.png" ) ,
				array('license_area'=> null ,'license_role'=> null ,'type'=> 'button' ,'action'=> 'API.logout();Context.getMainPage();' ,'title'=> "Logout" ,'icon'=> 'images/' ."logout.png" ) 
			);
			$ptn = readPattern($_SESSION[ "service_dir" ]  .'/pattern/' .'ptn_'. "mainpage" .'.php' );
			$ptn_button = readPattern($_SESSION[ "service_dir" ]  .'/pattern/' .'ptn_'. 'item_button' .'.php' );
			$tools_str = "";
			if(is_array($tools)){
				foreach($tools as $tool){
					if($tool['type'] == "button"){
						if($tool['license_area'] == null || (Session::getRoleOfArea( $tool['license_area'] ) >=  $tool['license_role'] ) ){
							$ptn_button->title = $tool['title'];
							$ptn_button->icon = $tool['icon'];
							$ptn_button->action = "";
							$ptn_button->action = $tool['action'];
							$tools_str.=  $ptn_button ->publish() ;
						}
					}
				}
				$ptn->tool_panel = $tools_str;
			}
			$rs->addData("content", $ptn ->publish() );
			$rs->return = true;
		}else if($method == "signup"){
			$mailaddress = $_REQUEST["email_address"];
			$password = $_REQUEST["password"];
			if(strlen($mailaddress) > 0){
				$srs = FunctionTransaction::registerAccount($mailaddress, $password);
				$rs->merge($srs);
				if($srs->return){
					$srs = FunctionTransaction::confirmRegistration($mailaddress, $rs->data["code"]);
					if($srs->return){
						$rs->return = true;
						if($lang != "bin"){
							$rs->addData("content",callService("mainpage",null));
						}else{
						}
					}
				}
			}
		}else if($method == "confirm"){
			$mailaddress = $_REQUEST["email_address"];
			$confirm_code = $_REQUEST["confirm_code"];
			if(strlen($mailaddress) > 0){
				$srs = FunctionTransaction::confirmRegistration($mailaddress, $confirm_code);
				if($srs->return){
					$srs->addData("success","<div>Confirm successfull, you can use your account now.</div>");
					$ptn = readPattern($_SESSION[ "service_dir" ]  .'/pattern/' .'ptn_'. "mainpage" .'.php' );
					$srs->addData("content",  $ptn ->publish() );
				}else{
					{Error::getInstance() ->addError( 0 , "Confirm registration fail! Please check again." );} ;
				}
				$rs->merge($srs);
			}else{
				{Error::getInstance() ->addError( 1  , "Email address empty!" );} ;
			}
		}else if($method == "checkLogin"){
			if(FunctionSession::isLogin()){
				$rs->return = true;
			}else{
				$rs->return = false;
			}
		}else if($method == "login"){
			$mailaddress = $this->args["email_address"];
			$password = $this->args["password"];
			if(strlen($mailaddress) > 0){
				$rss = FunctionSession::login($mailaddress,$password);
				$rs->merge($rss);
				if(Session::isLogin()){
					$rs->return = true;
					if($lang != "bin"){
						$rs->addData("userid",Session::getID());
					}else{
						$id = Session::getID();
						$identify = unpack('C*', Session::getIdentify() ) ;
						$size = 0;
						$size += 4 ;
						$size += 1  + count($identify);
						$buf = ByteBuffer::allocate( $size ) ;
						DataUtil::writeInt32( $buf , $id ) ;
						DataUtil::writeBBin( $buf , $identify ) ;
						$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
					}
				}
			}
		}else if($method == "loginGuest"){
			$guestid = $this->args["guestid"];
			$check_key = $this->args["md5"];
			$inappid = $this->args["inappid"];
			$app = FunctionData::readApp($inappid);
			if($app != null){
				$str = $guestid.$inappid.$app->getSecretKey();
				$md5 = md5($str);
				if($md5 == $check_key){
					if(!FunctionData::checkGuestIDUsed($guestid)){
						FunctionTransaction::registerAGuest($guestid);
					}
					FunctionSession::loginGuest($guestid);
					$rs->return = true;
					if($lang == "bin"){
						$id = FunctionData::getGuestID($guestid);
						$buf = ByteBuffer::allocate( 4  ) ;
						DataUtil::writeInt32( $buf , $id ) ;
						$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
					}else{
					}
				}else{
					$rs->return = false;
					$rs->addData("content","false:".$guestid.":".$inappid.":".$app->getSecretKey().":".$md5);
				}
			}else{
				$rs->return = false;
				$rs->addData("content","false:".$inappid);
			}
		}else if($method == "logout"){
			FunctionSession::logout();
			$rs->return = true;
		}else if($method == "add_group"){
			$group_name = $_REQUEST['group_name'];
			$rs->merge(FunctionGroup::addSystemGroup($group_name));
		}else if($method == "request_addarea"){
		}else if($method == "add_area"){
			$area_name = $_REQUEST['area_name'];
			$area_type = $_REQUEST['area_type'];
			if(strlen($area_name) > 0){
				if($area_type == "system"){
					$rs->merge(FunctionArea::addSystemArea($area_name));
				}else if($area_type == "user"){
					$rs->merge(FunctionArea::addUserArea($area_name));
				}
			}
		}else if($method == "add_license"){
			$area_name = $_REQUEST["area"];
			$group_name = $_REQUEST["group"];
			$license = $_REQUEST["role"];
			$license_obj = new License($area_name,$license);
			$rs->merge(FunctionGroup::setLicenseToGroup($license_obj,$group_name));
		}else if($method == "create_app"){
			$app_name = $_REQUEST["app_name"];
			$app_directory = $_REQUEST["app_directory"];
			$rs->merge(FunctionApp::createApp($app_name,$app_directory));
		}else if($method == "getApps"){
			if((Session::getRoleOfArea( "AccountManagement"  ) >=  (1)  ) ){
				$apps_id = FunctionData::getAppManager()->getAppsID();
				if(is_array($apps_id)){
					foreach($apps_id as $appid){
						$app = FunctionData::readApp($appid);
						$rs->addData($appid,$app->getName());
						$rs->addData($appid."_directory",$app->getDirectory());
						$rs->addData($appid."_secretcode",$app->getSecretKey());					
					}
				}
			}else{
				{Error::getInstance() ->addError( 16  , "You do not have permission to do this action." );} ;
			}
		}else if($method == "add_usertogroup"){
			$group_name = $_REQUEST["group"];
			$user_mail = $_REQUEST["email_address"];
			$rs->merge(FunctionGroup::addUserToGroup($user_mail,$group_name));
		}else if($method == "changePassword"){
			$old_password = $_REQUEST['old_password'];
			$new_password = $_REQUEST['new_password'];
			$new_passconfirm = $_REQUEST['new_passconfirm'];
			if(strlen($new_password) > 0 && $new_password == $new_passconfirm){
				$rs->merge(FunctionTransaction::changePassword($old_password,$new_password));
			}else{
				{Error::getInstance() ->addError( ERROR_WRONG_PASSWORD , "Password must not empty and password and confirm must be match" );} ;
			}
		}else if($method == "getCertificate"){
			$device_id = $this->args['did'];
			$device_name = $this->args['dname'];
			$srs = FunctionSession::getCertificate($device_id,$device_name);
			$rs->merge($srs);
			if($lang == "bin"){
				$cer = $srs->data["certificate"];
				if($cer != null){
					$cer_bytes = unpack('C*', $cer ) ;
					if(is_array($cer_bytes)){
						$rs->return = true;
						$size = 0;
						$size += 2  + count($cer_bytes);
						$buf = ByteBuffer::allocate( $size ) ;
						DataUtil::writeSBin( $buf , $cer_bytes ) ;
						$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
					}
				}
			}
		}else if($method == "loginByCertificate"){
			$mail_address = $_REQUEST['email_address'];
			$device_id = $_REQUEST['did'];
			$cer = $_REQUEST["cer"];
			$subrs = FunctionSession::loginWithCertificate($mail_address,$device_id,$cer);
			$rs->merge($subrs);
			$rs->return = $subrs->return;
			if($rs->return){
				if($lang == "bin"){
					$size = 4 ;
					$buf = ByteBuffer::allocate( $size ) ;
					DataUtil::writeInt32( $buf , Session::getID() ) ;
					$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
				}
			}
		}else if($method == "removeCertificate"){
			if(Session::isLogin()){
				$mail_address = FunctionSession::getEmailAddress();
				$mac_address = $_REQUEST['mac_address'];
				$cers = FunctionData::readCertificates($mail_address);
				if($cers->removeCertificate($mac_address)){
					FunctionData::writeCertificates($mail_address,$cers);
					$rs->return = true;
				}
			}else{
				{Error::getInstance() ->addError( 17  , "please login first!" );} ;
			}
		}else if($method == "addFriend"){
			if(Session::isLogin()){
				$fid = $this->args["fid"];
				if(FunctionSession::addFriend($fid)){
					FunctionSession::addFriendToUser(FunctionData::getIdentifyFromId($fid),Session::getID());
					$rs->return = true;
				}else{
					$rs->return = false;
				}
			}else{
				{Error::getInstance() ->addError( 17  , "please login first!" );} ;
				$rs->return = false;
			}
		}else if($method == "getFriends"){
			$revision = $this->args["revision"];
			if(Session::isLogin()){
				$friends = FunctionSession::getFriends();
				if($friends != null){
					if($revision != $friends->getRivision()){
						$rs->return = true;
						if($lang == "bin"){
							$fids = $friends->getFriendsID();
							$size = 0;
							$size += 4 ; 
							$size += 4 ; 
							$infos = array();
							if(is_array($fids)){
								foreach($fids as $fid){
									$size += 4 ; 
									$name = unpack('C*', FunctionData::getIdentifyFromId($fid) ) ;
									$size += 1  + count($name);
									$infos[] = array('id'=>$fid,'name'=>$name);
								}
							}
							$buf = ByteBuffer::allocate( $size ) ;
							DataUtil::writeInt32( $buf , $friends->getRivision() ) ;
							DataUtil::writeInt32( $buf , count($infos) ) ;
							if(is_array($infos)){
								foreach($infos as $info){
									DataUtil::writeInt32( $buf ,  $info['id'] ) ;
									DataUtil::writeBBin( $buf , $info['name'] ) ;
								}
							}
							$rs->addData('content',implode(array_map("chr",   $buf ->_array()  )) );
						}
					}else{
						$rs->return = false;
					}
				}else{
					$rs->return = false;
				}
			}else{
				{Error::getInstance() ->addError( 17  , "please login first!" );} ;
				$rs->return = false;
			}
		}else if($method == "synFBAccount"){
			$appid = $this->args["aid"];
			$mrg = ($this->args["mrg"] == "true")?true:false;
			$fbid = $this->args["fid"];
			$fbmail = $this->args["femail"];
			$fbname = $this->args["fname"];
			$aid = FunctionData::getIdByFacebookAccount($fbid);
			if($aid == -1){
				if($mrg && Session::isLogin()){
					if(FunctionData::mergeFbAccountToID(Session::getID(), $fbid)){
						$rs->return = true;
						if($lang == "bin"){
							$size = 4 ;
							$buf = ByteBuffer::allocate( $size ) ;
							DataUtil::writeInt32( $buf , Session::getID() ) ;
							$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
						}
					}else{
						{Error::getInstance() ->addError( 21  , "User has been login but merge facebook account fail!" );} ;
					}
				}else{
					if(Session::isLogin()){
						Session::logout();
					}
					$id = FunctionData::readAccountId($fbmail);
					if($id == -1){
						$srs = FunctionTransaction::registerAccount($fbmail, "");
						$rs->merge($srs);
						if($srs->return){
							$srs = FunctionTransaction::confirmRegistration($fbmail, $rs->data["code"]);
							if($srs->return){
								$id = FunctionData::getIDFromIdentify($fbmail);
							}else{
								{Error::getInstance() ->addError( 22  , "Confirm account fail!" );} ;
							}
						}else{
							{Error::getInstance() ->addError( 23  , "Registation gone fail!" );} ;
						}
					}
					if($id > -1){
						if(FunctionData::mergeFbAccountToID($id, $fbid)){
							if(FunctionSession::loginWithFb($fbid)){
								$rs->return = true;
								if($lang == "bin"){
									$size = 4 ;
									$buf = ByteBuffer::allocate( $size ) ;
									DataUtil::writeInt32( $buf , Session::getID() ) ;
									$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
								}
							}else{
								{Error::getInstance() ->addError( 14  , "Register successfull but can't login" );} ;
							}
						}else{
							{Error::getInstance() ->addError( 21  , "Register successfull but can't merge with facebook account!" );} ;
						}
					}else{
						{Error::getInstance() ->addError( 12  , "System Error!" );} ;
					}
				}				
			}else{
				if(Session::isLogin()){
					Session::logout();
				}
				if(FunctionSession::loginWithFb($fbid)){
					$rs->return = true;
					if($lang == "bin"){
						$size = 4 ;
						$buf = ByteBuffer::allocate( $size ) ;
						DataUtil::writeInt32( $buf , Session::getID() ) ;
						$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
					}
				}else{
					{Error::getInstance() ->addError( 12  , "System Error!" );} ;
				}			
			}
		}else if($method == "synFbFriends"){
			$fids_str = "".$this->args["ids"];
			$fids = explode(",", $fids_str);
			if(is_array($fids)){
				$ids = array();
				foreach($fids as $fid){
					$id = FunctionData::getIdByFacebookAccount($fid);
					if($id > -1){
						$bin_name = unpack('C*', $fid ) ;
						$ids[] = array("id"=>$id,"fid"=>$bin_name);
					}
				}
				$size = 0;
				$size += 4 ;
				if(is_array($ids)){
					foreach($ids as $rid){
						$size += 4 ;
						$size += 1 ;
						$size += count($rid["fid"]);
					}
					$buf = ByteBuffer::allocate( $size ) ;
					DataUtil::writeInt32( $buf ,  count($ids) ) ;
					foreach($ids as $rid){
						DataUtil::writeInt32( $buf ,  $rid["id"] ) ;
						DataUtil::writeBBin( $buf ,  $rid["fid"] ) ;
					}
					$rs->return = true;
					$rs->addData("content", implode(array_map("chr",   $buf ->_array()  )) );
				}
			}
		}else{
			{Error::getInstance() ->addError( 0 , "Unknown request!" );} ;
		}
		return  $rs ->publish( $lang ) ;
	}
}
?>